import json

import requests


class RequestsUtil:
    session = requests.session()
    def request(self, method, url, data, headers, **kwargs):
        # 验证 method 是否为合法的 HTTP 方法
        method = str(method).lower()
        if method not in ['get', 'post', 'put', 'delete', 'patch']:
            raise ValueError(f"Unsupported HTTP method: {method}")
        # 验证 url 是否为合法 URL
        if not isinstance(url, str) or not url.startswith(('http://', 'https://')):
            raise ValueError("URL地址不合法")
        try:
            # 处理 GET 请求
            if method == 'get':
                response = RequestsUtil.session.request(method, url=url, params=data, headers=headers, **kwargs)
            else:
                # 将 data 转换为 JSON 字符串（如果 data 存在）
                if data is not None:
                    data = json.dumps(data)
                response = RequestsUtil.session.request(method, url=url, data=data, headers=headers, **kwargs)
            return response
        except requests.exceptions.RequestException as e:
            # 捕获并处理请求异常
            raise RuntimeError(f"请求失败: {e}")